<template>
  <div class="upload-container">
    <h2>上传视频</h2>

    <!-- el-upload 拖拽上传区域 -->
    <el-upload class="upload-demo" drag action="#" :auto-upload="false" :on-change="handleFileUpload" :limit="1"
      :on-exceed="handleExceed" accept="video/*">
      <el-icon name="upload" />
      <div class="el-upload__text">将视频拖到此处，或<em>点击上传</em></div>
      <div class="el-upload__tip" slot="tip">只能上传 MP4/WebM/Ogg 格式，且不超过50MB</div>
    </el-upload>
    <el-input v-model="videoRemark" placeholder="请输入视频备注" style="margin-top: 20px;" />

    <!-- 上传按钮 -->
    <el-button @click="uploadVideo" type="primary" style="margin-top: 20px;">上传</el-button>

    <!-- 视频预览 -->
    <div v-if="previewUrl" class="video-preview">
      <h3>视频预览</h3>
      <video :src="previewUrl" controls width="100%" height="240"></video>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      selectedFile: null,
      previewUrl: null,
      videoRemark: '' // 用于存储备注内容
    };
  },
  methods: {
    handleFileUpload(file) {
      this.selectedFile = file.raw; // 获取 File 对象

      // 清理旧的预览链接
      if (this.previewUrl) {
        URL.revokeObjectURL(this.previewUrl);
      }

      // 创建新的预览链接
      if (this.selectedFile) {
        this.previewUrl = URL.createObjectURL(this.selectedFile);
      }
    },
    uploadVideo() {
      if (!this.selectedFile) {
        this.$message.warning("请选择一个视频文件");
        return;
      }

      const validTypes = ['video/mp4', 'video/webm', 'video/ogg'];
      const isValidType = validTypes.includes(this.selectedFile.type);
      if (!isValidType) {
        this.$message.warning("只能上传 MP4/WebM/Ogg 格式的视频");
        return;
      }

      if (this.selectedFile.size > 50 * 1024 * 1024) {
        this.$message.warning("视频大小不能超过50MB");
        return;
      }

      let videos = JSON.parse(localStorage.getItem('uploadedVideos')) || [];
      videos.push({
        name: this.selectedFile.name,
        url: this.previewUrl,
        remark: this.videoRemark // 新增：保存备注
      });

      localStorage.setItem('uploadedVideos', JSON.stringify(videos));
      this.$message.success("视频上传成功！");

      // 清空预览和备注
      this.previewUrl = null;
      this.selectedFile = null;
      this.videoRemark = '';
    },
    handleExceed(files, fileList) {
      this.$message.warning("最多只能选择一个视频文件");
    }
  },
  beforeUnmount() {
    if (this.previewUrl) {
      URL.revokeObjectURL(this.previewUrl);
    }
  }
};
</script>

<style scoped>
.upload-container {
  padding: 20px;
  max-width: 600px;
  margin: auto;
}

.upload-box {
  border: 2px dashed #ccc;
  border-radius: 8px;
  padding: 20px;
  text-align: center;
  background-color: #f9f9f9;
  margin-bottom: 20px;
  cursor: pointer;
  transition: border-color 0.3s ease;
}

.upload-box:hover {
  border-color: #888;
}

.placeholder {
  color: #aaa;
  font-size: 14px;
  margin-top: 10px;
}

.video-preview {
  margin-top: 30px;
}
</style>